package com.app.mingluxing.ui;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.app.mingluxing.R;
import com.app.mingluxing.adapter.MyAdapter;
import com.app.mingluxing.babytree.ReleaseActivity;
import com.app.mingluxing.base.BaseActivity;
import com.app.mingluxing.bean.ResultBaseBean;
import com.app.mingluxing.bean.VerRes;
import com.app.mingluxing.db.DatabaseManager;
import com.app.mingluxing.fragment.ChatFragment;
import com.app.mingluxing.fragment.HomeFragment;
import com.app.mingluxing.fragment.LocationFragment;
import com.app.mingluxing.fragment.MyFragement;
import com.app.mingluxing.message.ChoosePhotoActivity;
import com.app.mingluxing.net.HttpUtil;
import com.app.mingluxing.utils.CommonUtils;
import com.app.mingluxing.utils.Constant;
import com.app.mingluxing.utils.DensityUtil;
import com.app.mingluxing.utils.LogUtil;
import com.app.mingluxing.widget.ActionSheetDialog;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.umeng.update.UmengUpdateAgent;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.framework.ShareSDK;
import de.greenrobot.event.EventBus;


/**
 * Created by Administrator on 2015/7/14.
 */
public class HomeActivity extends BaseActivity {

//    private FrameLayout fl_base;
    /**
     * fragment 管理者
     */
    private FragmentManager manager;
    private HomeFragment homeFragment;
    private LocationFragment locationFragment;
    //    private MessageFragment messageFragment;
    private MyFragement myFragement;
    private TextView tv_message;
    private TextView tv_child;
    private TextView tv_baby_tree;
    private TextView tv_my;
    private ImageView iv_home;
    private ImageView iv_location;
    private ImageView iv_photo;
    private ImageView iv_message;
    private ImageView iv_my;
    /*拍照的文件保存的位置*/
    public File currentFile;
    /*相册选择的code*/
    private static final int PHOTO_ALBUM_CODE = 0x1031;
    /*拍照的code*/
    private static final int TAKE_PHOTO_CODE = 0x1032;
    //裁剪处理图片后的code
    private static final int PHOTO_HANDLE_RESOULT_MY = 0x34;
//    //选择孩子的code
//    private static final int CHOOSE_BABY_CODE = 10001;

    private ViewGroup ic_home_bottom;
    private Intent mIntent;

    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private MyLocationListenner myListener = new MyLocationListenner();
    // 定位相关
    private LocationClient mLocClient;
    //是否是第一次定位
    private boolean isFirstLoc = true;
    //    private HttpUtils utils;
    private TextView tv_msg_count;//未读消息红点
    private Uri uritempFile;
    private ChatFragment chatFragment;

    //private Token token;
//    private String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        setContentView(R.layout.activity_home);
//        mApplication.addActivity(this);

        ShareSDK.initSDK(this);

        //开启服务,登录mqtt
        mApplication.loginMqtt();

        initWidget();

        initFragment();



////        友盟检查更新
        UmengUpdateAgent.setUpdateOnlyWifi(false);
        UmengUpdateAgent.update(this);
//        UpdateConfig.setDebug(true);//debug模式,发布时删除

        //获取配置版本信息
        getVersionInfo();

//        //获取未读消息的数量
//        getMessageCount();

        EventBus.getDefault().register(this);
    }


    /**
     * 更新小红点
     *
     * @param msb
     */
    public void onEventMainThread(String msb) {

        if (Constant.UPDATE_RED_COUNT.equals(msb))
            setRedCount();

    }

    @Override
    protected void onResume() {
        super.onResume();

        LogUtil.e("tag", getClass().getName() + "   onresume  ");

        // 在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理

        if (mBaiduMap != null)
            mMapView.onResume();

        setRedCount();

    }


    // 设置红点个数
    public void setRedCount() {

        int sum = DatabaseManager.getInstance().queryAllUnReadCount(this, sp.getString(Constant.USERID, ""));

        if (sum == -100)
            return;

        if (sum > 99) sum = 99;
        tv_msg_count.setText(sum + "");
        tv_msg_count.setVisibility(sum > 0 ? View.VISIBLE : View.INVISIBLE);

    }

    /**
     * 获取配置版本信息
     */
    private void getVersionInfo() {

        final JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("ver", getAppVersionName(this));
        j.put("build", sp.getString(Constant.BUILD, ""));

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.WEB_ROOT + Constant.VERSION, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                LogUtil.e("tag", "版本信息==" + response);

                try {

                    VerRes verRes = JSONObject.parseObject(response, VerRes.class);

                    if (verRes.code == 1011) {//1011 需要更新本地配置文件

                        SharedPreferences.Editor edit = sp.edit();
                        //保存服务器的配置版本
                        edit.putString(Constant.BUILD, verRes.build);
                        edit.apply();

                        if (verRes.data != null) {

                            //保存配置信息到本地
                            CommonUtils.fileSave(Constant.VERDATA, verRes);

                        }

                    } else if (verRes.code == 1008) {
                        //提示版本更新
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

            }

        }) {

            protected Map<String, String> getParams() {
                Map<String, String> param = new HashMap<String, String>();
                param.put("data", j.toJSONString());

                return param;
            }

        };

        //把请求加入队列
        mApplication.addToRequestQueue(stringRequest, getClass().getName());

    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
//            versioncode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            LogUtil.e("tag", e);
        }
        return versionName;
    }

    private void initWidget() {

        RelativeLayout rl_message = (RelativeLayout) findViewById(R.id.rl_message);
        RelativeLayout rl_child = (RelativeLayout) findViewById(R.id.rl_child);
        RelativeLayout rl_baby_tree = (RelativeLayout) findViewById(R.id.rl_baby_tree);
        RelativeLayout rl_my = (RelativeLayout) findViewById(R.id.rl_my);

        iv_home = (ImageView) findViewById(R.id.iv_home);
        iv_location = (ImageView) findViewById(R.id.iv_location);
        iv_photo = (ImageView) findViewById(R.id.iv_photo);
        iv_message = (ImageView) findViewById(R.id.iv_message);
        iv_my = (ImageView) findViewById(R.id.iv_my);

        ic_home_bottom = (ViewGroup) findViewById(R.id.ic_home_bottom);

        tv_message = (TextView) findViewById(R.id.tv_message);
        tv_child = (TextView) findViewById(R.id.tv_child);
        tv_baby_tree = (TextView) findViewById(R.id.tv_baby_tree);
        tv_my = (TextView) findViewById(R.id.tv_my);

        tv_msg_count = (TextView) findViewById(R.id.tv_msg_count);

        rl_message.setOnClickListener(this);
        rl_child.setOnClickListener(this);
        rl_baby_tree.setOnClickListener(this);
        rl_my.setOnClickListener(this);
        iv_photo.setOnClickListener(this);

//        getMsgCount();

        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView);

        // 获取地图控件引用
        mBaiduMap = mMapView.getMap();

        getMyLocation();

    }

    /**
     * 隐藏底部按钮
     */
    public void hitButtom() {
        ic_home_bottom.setVisibility(View.GONE);
    }

    /**
     * 显示底部按钮
     */
    public void showButtom() {
        ic_home_bottom.setVisibility(View.VISIBLE);
    }

    private void initFragment() {

        manager = getFragmentManager();

        iv_home.setSelected(true);
        tv_message.setTextColor(getResources().getColor(R.color.red));

        chooseFragment(0);
    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.rl_message:

                //把所有的图标都变灰
                setSelectFalse();
                //消息
                chooseFragment(0);

                //TODO 改变字体颜色和图片
                iv_home.setSelected(true);
                tv_message.setTextColor(getResources().getColor(R.color.red));
                break;

            case R.id.rl_child:

                //把所有的图标都变灰
                setSelectFalse();
                //孩子
                chooseFragment(1);

                iv_location.setSelected(true);
                tv_child.setTextColor(getResources().getColor(R.color.red));
                break;
            case R.id.rl_baby_tree:

                //把所有的图标都变灰
                setSelectFalse();
                //宝宝树
                chooseFragment(3);

                iv_message.setSelected(true);
                tv_baby_tree.setTextColor(getResources().getColor(R.color.red));
                break;
            case R.id.rl_my:

                //把所有的图标都变灰
                setSelectFalse();
                //我的
                chooseFragment(4);

                iv_my.setSelected(true);
                tv_my.setTextColor(getResources().getColor(R.color.red));

                break;
            case R.id.iv_photo:

                showChoose();

                break;

        }
    }

    /**
     * 选择对应的fragment
     *
     * @param index 对应的fragment的角标
     */
    private void chooseFragment(int index) {

        FragmentTransaction transaction = null;
        if (manager != null) {
            transaction = manager.beginTransaction();
        }
        // 先移除掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
//        removeFragments(transaction);

        if (transaction == null)
            return;

        switch (index) {

            case 0:
                //消息
                if (homeFragment == null)
                    homeFragment = new HomeFragment();

                if (!homeFragment.isAdded()) {
                    transaction.replace(R.id.fl_base, homeFragment, Constant.NEWS);
                }

                break;

            case 1:

                if (locationFragment == null)
                    locationFragment = new LocationFragment();

                if (!locationFragment.isAdded()) {
                    transaction.replace(R.id.fl_base, locationFragment, Constant.CHILD);
                } else {
                    locationFragment.reBottonLocation();
                }

                break;

//            case 2:
//
//                break;
            case 3:

                if (chatFragment == null)
                    chatFragment = new ChatFragment();

                if (!chatFragment.isAdded()) {
                    transaction.replace(R.id.fl_base, chatFragment, Constant.NEWS);
                }
                break;
            case 4:

                if (myFragement == null)
                    myFragement = new MyFragement();

                if (!myFragement.isAdded()) {
                    transaction.replace(R.id.fl_base, myFragement, Constant.MY);
                }

                break;

        }

        if (transaction != null) {
//            transaction.commit();
            transaction.commitAllowingStateLoss();
        }

    }

//    /**
//     * 移除fragment
//     *
//     * @param transaction
//     */
//    private void removeFragments(FragmentTransaction transaction) {
//        if (transaction == null)
//            return;
//
//        if (homeFragment != null) {
//            transaction.remove(homeFragment);
//        }
//        if (locationFragment != null) {
//            transaction.remove(locationFragment);
//        }
//        if (messageFragment != null) {
//            transaction.remove(messageFragment);
//        }
//        if (myFragement != null) {
//            transaction.remove(myFragement);
//        }
//
//    }

    /**
     * 弹出发布宝宝树选择照片的对话框
     */
    @Deprecated
    protected void showChoose() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
//                                 拍照
                                getTakePhoto();

                            }

                        })
                .addSheetItem("去相册选择", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
//                                 从相册中选择
                                getFromPhotoAlbum();
                            }
                        }).show();

    }


    /**
     * 弹出更换首页背景选择照片的对话框
     */
    @Deprecated
    public void showHomeChoose() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
//                                 拍照
                                getHomeTakePhoto();

                            }

                        })
                .addSheetItem("去相册选择", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
//                                 从相册中选择
                                getHomeFromPhotoAlbum();

                            }
                        }).show();

    }


    /**
     * 拍照
     */
    private void getHomeTakePhoto() {

        String cacheDir = Environment.getExternalStorageDirectory().getPath() + "/mlxCache";
        File photoFile = new File(cacheDir);
        //文件夹不存在就创建文件夹
        if (!photoFile.exists()) {
            photoFile.mkdirs();
        }
        //创建存放图片的jpg文件
        com.app.mingluxing.ui.HomeActivity h = (com.app.mingluxing.ui.HomeActivity) this;

        h.currentFile = new File(photoFile, System.currentTimeMillis() + ".jpg");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(h.currentFile));
        startActivityForResult(intent, TAKE_PHOTO_CODE_HOME);

    }

    /**
     * 从相册中选择更换首页背景
     */
    private void getHomeFromPhotoAlbum() {

        Intent mIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(mIntent, PHOTO_ALBUM_CODE_HOME);

    }

    /**
     * 拍照
     */
    private void getTakePhoto() {

        String cacheDir = Environment.getExternalStorageDirectory().getPath() + Constant.PHOTO_PATH;
        File photoFile = new File(cacheDir);
        //文件夹不存在就创建文件夹
        if (!photoFile.exists()) {
            photoFile.mkdirs();
        }
        //创建存放图片的jpg文件
        currentFile = new File(photoFile, System.currentTimeMillis() + ".jpg");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentFile));
        startActivityForResult(intent, TAKE_PHOTO_CODE);
    }

    /**
     * 从相册中选择
     */
    private void getFromPhotoAlbum() {

        Intent intent = new Intent(this, ChoosePhotoActivity.class);
        startActivityForResult(intent, PHOTO_ALBUM_CODE);

    }


    /*相册选择的code*/
    private static final int PHOTO_ALBUM_CODE_HOME = 0x10031;
    /*拍照的code*/
    private static final int TAKE_PHOTO_CODE_HOME = 0x10032;
//    private static final int PATH_PHOTO = 10033;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case TAKE_PHOTO_CODE: //拍照跳转发布宝宝树页面
//                if (data == null)
//                    return;

//                String path = currentFile.getPath();
//
//                LogUtil.e("tag", "路径path===" + path + ", 存在吗: " + currentFile.exists());

                if (currentFile != null && currentFile.exists()) {

                    mIntent = new Intent(this, ReleaseActivity.class);
                    mIntent.putExtra("take_photo", currentFile.getPath());
                    currentFile = null;
                    startActivity(mIntent);

                }

                break;

            case PHOTO_ALBUM_CODE://相册选择跳转发布宝宝树页面

                if (data == null) {
                    MyAdapter.mSelectedImage.clear();
                    return;
                }

                //获取到传过来的图片的集合
                ArrayList<String> tempPhotos = data.getStringArrayListExtra("selectedPhotos");
//                String path = data.getStringExtra("path");
                mIntent = new Intent(this, ReleaseActivity.class);
                mIntent.putStringArrayListExtra("choose_photo", tempPhotos);
//                mIntent.putExtra("delete_path",path);
                startActivity(mIntent);

                break;

//            case CHOOSE_BABY_CODE:   //选择孩子
//                if (data == null)
//                    return;
//                String childId=data.getStringExtra("children");  b
//                SharedPreferences.Editor editor=sp.edit();
//                editor.putString("childId",childId);
//                editor.commit();

//        }
            case PHOTO_ALBUM_CODE_HOME://相册选择 修改首页宝宝树背景图片

                if (data == null)
                    return;

                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);//图片路径
                cursor.close();


                //裁剪图片
                startPhotoZoom(Uri.fromFile(new File(picturePath)));

//                //上传图片
//                if (homeFragment != null) {
//                    homeFragment.getUploadToken(CommonUtils.compressByte(CommonUtils.getBitmapFromPath(picturePath)));
//                }

                break;
            case TAKE_PHOTO_CODE_HOME: //拍照 修改首页宝宝树背景图片

                startPhotoZoom(Uri.fromFile(currentFile));
//                currentFile = null;

                break;

            case PHOTO_HANDLE_RESOULT_MY: //图片处理后的 code

//                if (data==null)
//                    return;
//
//                Bundle extras = data.getExtras();
//                if (extras != null) {
//
//                    Bitmap photo = extras.getParcelable("data");

                try {
                    //上传图片
                    if (homeFragment != null) {
                        homeFragment.getUploadToken(CommonUtils.compressByte(BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile))));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

//                    getUploadToken(CommonUtils.compressByte(photo));

//                }

                break;

        }
    }

    /**
     * 裁剪图片
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");

        int width = CommonUtils.getScreenSize(this)[0];
//
        int heigh = DensityUtil.dip2px(this, 230);
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", width);
        intent.putExtra("aspectY", heigh);

//        LogUtil.e("tag", "宽:" + width + ",高:" + heigh);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", width);
        intent.putExtra("outputY", heigh);
//        intent.putExtra("return-data", true);
        uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//        Uri.par

        startActivityForResult(intent, PHOTO_HANDLE_RESOULT_MY);
    }

    /**
     * 把所有的图标都变灰
     * 字体还原
     */
    private void setSelectFalse() {

        iv_home.setSelected(false);
        iv_location.setSelected(false);
        iv_photo.setSelected(false);
        iv_message.setSelected(false);
        iv_my.setSelected(false);

        tv_message.setTextColor(getResources().getColor(R.color.text_color));
        tv_child.setTextColor(getResources().getColor(R.color.text_color));
        tv_baby_tree.setTextColor(getResources().getColor(R.color.text_color));
        tv_my.setTextColor(getResources().getColor(R.color.text_color));

    }

    private long mPressedTime = 0;


    @Override
    public void onBackPressed() {

        long mNowTime = System.currentTimeMillis();//获取第一次按键时间

        if ((mNowTime - mPressedTime) > 2000) {//比较两次按键时间差

            showToast("再按一次退出程序");

            mPressedTime = mNowTime;

        } else {//退出程序

            finish();
            mApplication.exit();

        }
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

//            LogUtil.e("tag", "城市:" + location.getCity());
            //保存城市信息
            SharedPreferences.Editor edit = sp.edit();
            edit.putString(Constant.CITYNAME, location.getCity());
            edit.apply();

            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null)
                return;
            MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();

            mApplication.myLatitude = location.getLatitude();
            mApplication.myLongitude = location.getLongitude();

            mBaiduMap.setMyLocationData(locData);

            if (isFirstLoc) {
                isFirstLoc = false;
//                //如果未绑定设备则定位到我的位置,否则定位到手表的位置
//                if (TextUtils.isEmpty(currentWatchId)) {

                try {
                    LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                    MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                    if (mBaiduMap != null)
                        mBaiduMap.animateMapStatus(u);
                } catch (Exception e) {
                    e.printStackTrace();
                }

//                }
            }

        }

    }

    /**
     * 获取到我的当前位置
     */
    private void getMyLocation() {
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_center_point_my);
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
//       //定位的点击事件
//        mBaiduMap.setOnMyLocationClickListener(new OnMyLocationClickListener() {
//
//            @Override
//            public boolean onMyLocationClick() {
//
//                LatLng latLng = new LatLng(myLatitude, myLongitude);
//                showMyLocationInfo(latLng);
//                return false;
//            }
//        });

        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);//需要返回地址,即 哪个市
        option.setAddrType("all"); //类型
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(100000);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        String zxingCode = intent.getStringExtra("zxing_code");

        if (CommonUtils.isNull(zxingCode))
            return;

        LogUtil.e("tag", "zxingCode= " + zxingCode);

        try {

            org.json.JSONObject info = new org.json.JSONObject(zxingCode);

            childBindClass(info.getString("classCode"));

        } catch (Exception e) {
            e.printStackTrace();
            showToast("无法解析出班级信息");
        }

    }

    /**
     * 绑定孩子班级
     *
     * @param classCode 班级code
     */
    private void childBindClass(String classCode) {

        JSONObject j = new JSONObject();
        j.put("id", sp.getString(Constant.CURRENTCHILDID, ""));
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("classCode", classCode);

        HttpUtil.setPostRequest("加载中...", this, Constant.WEB_ROOT + Constant.CHILDBINDCLASS,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            ResultBaseBean resultBaseBean = JSONObject.parseObject(str, ResultBaseBean.class);
                            if (resultBaseBean.code == Constant.STATUS_SUCCESS)

                                showToast("绑定班级成功!");
                            else
                                showToast(Constant.showErrorMsg(resultBaseBean.code, HomeActivity.this));


                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast(Constant.NODATA);
                        }

                    }
                }, null);

    }

    @Override
    public void onDestroy() {

        super.onDestroy();

        if (mBaiduMap != null)
            mMapView.onDestroy();

        mApplication.cancelPendingRequests(getClass().getName());
        EventBus.getDefault().unregister(this);

        ShareSDK.stopSDK(this);
    }

    public void onPause() {
        super.onPause();
        // 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        if (mBaiduMap != null)
            mMapView.onPause();

//        MobclickAgent.onPause(this);

    }




}
